package com.qqt.csr.im.controller;

import com.qqt.csr.common.exception.StatusCode;
import com.qqt.csr.common.idempotent.Idempotent;
import com.qqt.csr.common.idempotent.RequestKeyParam;
import com.qqt.csr.common.interceptor.auth.Authorize;
import com.qqt.csr.common.log.Log;
import com.qqt.csr.common.operalog.BusinessType;
import com.qqt.csr.common.operalog.LogLevel;
import com.qqt.csr.common.operalog.OperaLogSchema;
import com.qqt.csr.common.operalog.OperationLog;
import com.qqt.csr.common.session.SessionContextHolder;
import com.qqt.csr.common.utils.ServiceAssert;
import com.qqt.csr.common.vo.req.PageRequest;
import com.qqt.csr.common.vo.resp.ObjectResponse;
import com.qqt.csr.common.vo.resp.PageResponse;
import com.qqt.csr.im.entity.SensitiveWord;
import com.qqt.csr.im.entity.SensitiveWordRule;
import com.qqt.csr.im.service.sensitiveword.SensitiveWordRepoService;
import com.qqt.csr.im.service.sensitiveword.SensitiveWordRuleService;
import com.qqt.csr.im.service.sensitiveword.SensitiveWordService;
import com.qqt.csr.im.vo.req.*;
import com.qqt.csr.im.vo.resp.SensitiveWordRepoRespVO;
import com.qqt.csr.im.vo.resp.SensitiveWordRespVO;
import com.qqt.csr.im.vo.resp.SensitiveWordRuleCfgRespVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @Author: yang hao
 * @Date: 2024/10/15 15:52
 * @Description:
 **/
@Authorize
@Slf4j
@Tag(name = "敏感词管理")
@RestController
@RequestMapping("/sensitiveWord")
public class SensitiveWordController {
    @Autowired
    private SensitiveWordRuleService sensitiveWordRuleService;
    @Autowired
    private SensitiveWordRepoService sensitiveWordRepoService;
    @Autowired
    private SensitiveWordService sensitiveWordService;

    @PostMapping("/rule/set")
    @Operation(summary = "敏感词拦截显示规则设置")
    @Log(desc = "敏感词拦截规则设置")
    @OperationLog(level = LogLevel.HIGH, operationMenu = "敏感词管理", buttonName = "敏感词拦截规则设置", businessType = BusinessType.UPDATE)
    public ObjectResponse<String> setRuleConfig(@Validated @RequestBody SettingSensitiveWordRuleCfgReqVO req) {
        ServiceAssert.notNull(req, StatusCode.Common.NULL_ERROR.getCode(), "请求参数不能为空");
        String tenantId = SessionContextHolder.getHeaderInfo().getTenantId();
        sensitiveWordRuleService.setRuleConfig(tenantId, req.getShowType());
        return ObjectResponse.success(StringUtils.EMPTY);
    }

    @GetMapping("/rule/query")
    @Operation(summary = "获取敏感词拦截显示规则")
    public ObjectResponse<SensitiveWordRuleCfgRespVO> queryRuleConfig() {
        String tenantId = SessionContextHolder.getHeaderInfo().getTenantId();
        SensitiveWordRule ruleConfig = sensitiveWordRuleService.getRuleConfig(tenantId);
        return ObjectResponse.success(SensitiveWordRuleCfgRespVO.builder().showType(ruleConfig.getShowType()).build());
    }

    @Operation(summary = "敏感词库 分页查询")
    @PostMapping("/repo/page")
    public PageResponse<SensitiveWordRepoRespVO> page(@RequestBody  PageRequest<SensitiveWordPageQueryRepVO> repVO) {
        String tenantId = SessionContextHolder.getHeaderInfo().getTenantId();
        if(repVO.getData() == null){
            repVO.setData(new SensitiveWordPageQueryRepVO());
        }
        repVO.getData().setTenantId(tenantId);
        return sensitiveWordRepoService.page(repVO);
    }

    @Operation(summary = "敏感词库 详情")
    @GetMapping("/repo/detail/{id}")
    public ObjectResponse<SensitiveWordRepoRespVO> detail(@PathVariable("id") @NotNull(message = "词库id不能为空") Long id) {
        String tenantId = SessionContextHolder.getHeaderInfo().getTenantId();
        SensitiveWordRepoRespVO result = sensitiveWordRepoService.detail(tenantId, id);
        return ObjectResponse.success(result);
    }

    @Operation(summary = "敏感词库 保存")
    @PostMapping("/repo/save")
    @Log(desc = "新建敏感词库")
    @Idempotent(model = "sw:repo:add:")
    @OperationLog(level = LogLevel.HIGH, operationMenu = "敏感词管理", buttonName = "新建敏感词库", businessType = BusinessType.INSERT)
    public ObjectResponse<Boolean> save(@RequestBody @Validated SensitiveWordRepoAddReqVO reqVO) {
        String tenantId = SessionContextHolder.getHeaderInfo().getTenantId();
        boolean result = sensitiveWordRepoService.save(tenantId, reqVO);
        return ObjectResponse.success(result);
    }

    @Operation(summary = "敏感词库 更新")
    @PostMapping("/repo/update")
    @Log(desc = "更新敏感词库")
    @Idempotent(model = "sw:repo:update:")
    @OperationLog(level = LogLevel.HIGH, operationMenu = "敏感词管理", buttonName = "更新敏感词库", businessType = BusinessType.UPDATE)
    public ObjectResponse<Boolean> update(@RequestBody @Validated SensitiveWordRepoUpdateReqVO reqVO) {
        String tenantId = SessionContextHolder.getHeaderInfo().getTenantId();
        boolean result = sensitiveWordRepoService.update(tenantId, reqVO);
        return ObjectResponse.success(result);
    }

    @Operation(summary = "敏感词库 删除")
    @PostMapping("/repo/delete/{id}")
    @Log(desc = "删除敏感词库")
    @Idempotent(model = "sw:repo:delete:")
    @OperationLog(level = LogLevel.HIGH, operationMenu = "敏感词管理", buttonName = "删除敏感词库", businessType = BusinessType.DELETE)
    public ObjectResponse<Boolean> delete(@OperaLogSchema(desc = "敏感词库id") @RequestKeyParam @PathVariable("id") @NotNull(message = "词库id不能为空")
                                          Long id) {
        String tenantId = SessionContextHolder.getHeaderInfo().getTenantId();
        boolean result = sensitiveWordRepoService.delete(tenantId, id);
        return ObjectResponse.success(result);
    }

    @Operation(summary = "敏感词库 批量删除")
    @PostMapping("/repo/batch/delete")
    @Log(desc = "批量删除敏感词库")
    @Idempotent(model = "sw:repo:delete:")
    @OperationLog(level = LogLevel.HIGH, operationMenu = "敏感词管理", buttonName = "批量删除敏感词库", businessType = BusinessType.DELETE)
    public ObjectResponse<Boolean> batchDelete(@RequestBody @Validated SensitiveWordRepoDeleteReqVO reqVO) {
        String tenantId = SessionContextHolder.getHeaderInfo().getTenantId();
        boolean result = sensitiveWordRepoService.batchDelete(tenantId, reqVO);
        return ObjectResponse.success(result);
    }

    @PostMapping("/add")
    @Operation(summary = "新建敏感词")
    @Log(desc = "新建敏感词")
    @Idempotent(model = "sw:add:")
    @OperationLog(level = LogLevel.HIGH, operationMenu = "敏感词管理", buttonName = "新建敏感词", businessType = BusinessType.INSERT)
    public ObjectResponse<String> addSw(@Validated @RequestBody AddingSensitiveWordReqVO req) {
        ServiceAssert.notNull(req, StatusCode.Common.NULL_ERROR.getCode(), "请求参数不能为空");
        String tenantId = SessionContextHolder.getHeaderInfo().getTenantId();
        Long creatorId = SessionContextHolder.getHeaderInfo().getUserId();
        sensitiveWordService.add(req.getName(), req.getRepoId(), tenantId, creatorId);
        return ObjectResponse.success();
    }

    @PostMapping("/update")
    @Operation(summary = "编辑敏感词")
    @Log(desc = "编辑敏感词")
    @Idempotent(model = "sw:update:")
    @OperationLog(level = LogLevel.HIGH, operationMenu = "敏感词管理", buttonName = "编辑敏感词", businessType = BusinessType.UPDATE)
    public ObjectResponse<String> updateSw(@Validated @RequestBody UpdatingSensitiveWordReqVO req) {
        ServiceAssert.notNull(req, StatusCode.Common.NULL_ERROR.getCode(), "请求参数不能为空");
        String tenantId = SessionContextHolder.getHeaderInfo().getTenantId();
        SensitiveWord sensitiveWord = SensitiveWord.builder().id(req.getSwId()).name(req.getName()).tenantId(tenantId).build();
        sensitiveWordService.edit(sensitiveWord);
        return ObjectResponse.success();
    }

    @PostMapping("/delete")
    @Operation(summary = "删除敏感词")
    @Log(desc = "删除敏感词")
    @Idempotent(model = "sw:delete:")
    @OperationLog(level = LogLevel.HIGH, operationMenu = "敏感词管理", buttonName = "删除敏感词", businessType = BusinessType.DELETE)
    public ObjectResponse<String> deleteSw(@Validated @RequestBody DeletingSensitiveWordReqVO req) {
        ServiceAssert.notNull(req, StatusCode.Common.NULL_ERROR.getCode(), "请求参数不能为空");
        String tenantId = SessionContextHolder.getHeaderInfo().getTenantId();
        sensitiveWordService.delete(req.getSwIdList(), tenantId);
        return ObjectResponse.success();
    }

    @PostMapping("/enable")
    @Operation(summary = "启用或关闭敏感词")
    @Log(desc = "启用或关闭敏感词")
    @Idempotent(model = "sw:enable:")
    @OperationLog(level = LogLevel.HIGH, operationMenu = "敏感词管理", buttonName = "启用或关闭敏感词", businessType = BusinessType.UPDATE)
    public ObjectResponse<String> enableSw(@Validated @RequestBody UpdatingSensitiveWordEnableReqVO req) {
        ServiceAssert.notNull(req, StatusCode.Common.NULL_ERROR.getCode(), "请求参数不能为空");
        String tenantId = SessionContextHolder.getHeaderInfo().getTenantId();
        sensitiveWordService.enable(req.getSwId(), req.getEnable(), tenantId);
        return ObjectResponse.success();
    }

    @PostMapping("/queryPage")
    @Operation(summary = "查询敏感词列表")
    public PageResponse<SensitiveWordRespVO> querySwPage(@Validated @RequestBody PageRequest<QueryingSensitiveWordReqVO> req) {
        ServiceAssert.notNull(req, StatusCode.Common.NULL_ERROR.getCode(), "请求参数不能为空");
        String tenantId = SessionContextHolder.getHeaderInfo().getTenantId();
        if (req.getData() == null) {
            req.setData(new QueryingSensitiveWordReqVO());
        }
        req.getData().setTenantId(tenantId);
        return sensitiveWordService.queryPage(req);
    }
}
